<template>
  <div>
    <page-header
      :title="$t('addtask.NeueAufgabe')"
      :content="$t('addtask.InhalteVeröffentlichen')"
      class="PageHeader"
    />
    <page-main>
      <!-- 任务名称 -->
      <el-form ref="AddTaskFrom" :model="addTaskData" :rules="rules">
        <!-- <el-form-item :label="$t('addtask.suspendieren') + '：'">
          <el-switch
            v-model="addTaskData.status"
            class="ml-2"
            inline-prompt
            style="
              --el-switch-off-color: #13ce66;
              --el-switch-on-color: #ff4949;
            "
            :active-text="$t('addtask.ja')"
            :inactive-text="$t('addtask.nein')"
          />
        </el-form-item> -->
        <el-form-item
          :label="$t('addtask.Überprüfungsregeln') + '：'"
          prop="ruleId"
        >
          <el-select v-model="addTaskData.ruleId" style="width: 100%">
            <el-option
              v-for="item in ruleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('addtask.Aufgabenname') + '：'" prop="name">
          <el-input
            v-model="addTaskData.name"
            :placeholder="$t('addtask.BitteAufgabennamen')"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item
          :label="$t('addtask.Klasseauswählen') + '：'"
          prop="classes"
        >
          <el-select v-model="addTaskData.classes" multiple style="width: 100%">
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="$t('addtask.VerantwortungsbewussterLehrer') + '：'"
              prop="leader"
            >
              <el-radio-group
                v-model="addTaskData.leader"
                @change="changeleaderadd"
              >
                <el-radio
                  v-for="(item, index) in AdminTeacherList"
                  :key="index"
                  :label="item.userId"
                  >{{ item.nickname }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          :label="$t('addtask.TeilnehmendeLehrer') + '：'"
          prop="teacher"
        >
          <!-- 数据表格 -->
          <el-table
            :data="filterateParticipateTeacherList"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column
              :label="$t('addtask.NamedesLehrers') + '：'"
              prop="nickname"
            />
            <el-table-column
              :label="$t('addtask.Rolle') + '：'"
              prop="roleName"
            >
              <template #default="scope">
                <el-tag class="ml-2" :type="status(scope.row.roleName)">
                  {{ $t("addtask." + scope.row.roleName) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('addtask.JobID') + '：'"
              prop="codeId"
            />
          </el-table>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="$t('addtask.Anfangsdatum') + '：'"
              prop="startTime"
            >
              <div class="block">
                <el-date-picker
                  v-model="addTaskData.startTime"
                  type="datetime"
                  :placeholder="$t('addtask.BitteStartdatum')"
                />
              </div>
            </el-form-item>
            <el-form-item
              :label="$t('addtask.Kündigungszeit') + '：'"
              prop="endTime"
            >
              <div class="block">
                <el-date-picker
                  v-model="addTaskData.endTime"
                  type="datetime"
                  :placeholder="$t('addtask.BitteKündigungsdatum')"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('addtask.Aufgabenbeschreibung') + '：'">
              <el-input
                v-model="addTaskData.remark"
                :rows="4"
                type="textarea"
                :placeholder="$t('addtask.BitteAufgabenbeschreibung')"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item
              :label="$t('addtask.Anhängehochladen') + '：'"
              style="margin-top: 10px"
            >
              <file-upload
                :files="files"
                :progress-flag="progressFlag"
                :load-progress="loadProgress"
                @on-success="handleSuccess3"
                @on-change="handleChange"
                @on-remove="handleRemove"
              ></file-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="btnlink">
        <el-button
          v-throttle="submit"
          v-hasPerm="['courseinfo:task:add']"
          type="primary"
          size="large"
        >
          {{ $t("addtask.Jetztveröffentlichen") }}
        </el-button>
        <el-button v-throttle="cancellation" size="large">
          {{ $t("addtask.Abbrechen") }}
        </el-button>
      </div>
    </page-main>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Addtask",
  inheritAttrs: false,
});
// 导入引用
import FileUpload from "@/components/FileUpload/index.vue";
import PageHeader from "@/components/PageHeader/index.vue";
import PageMain from "@/components/PageMain/index.vue";
import router from "@/router";
import SparkMD5 from "spark-md5";
import { useAppStore } from "@/store/modules/app";
import { AddTaskDataRequest } from "@/api/task/types";
import { GetTeacherInfo } from "@/api/course";
import { getclasslist } from "@/api/student";
import { addExperimentTask } from "@/api/task";
import { verifyFile } from "@/utils/file";
import { formatDate } from "@/utils/formatTime";
import { uploadExpAnnex } from "@/api/file";
import { getRuleByCourseId } from "@/api/rule";
import { RulePageVO } from "@/api/rule/types";
import { useCourseStore } from "@/store/modules/course";
import { useRoute } from "vue-router";

const courseStore = useCourseStore();
const courseId = ref();
const appStore = useAppStore();
const files = ref([]); // 文件列表
const filesId = ref([]); // 上传文件列表id
const ids = ref<number[]>([]); // 行内id
const AddTaskFrom = ref(ElForm); // 添加任务表单
const classList = ref<classListType[]>(); // 获取班级列表
const TeacherList = ref<TeacherListType[]>(); // 教师总数
const AdminTeacherList = ref<TeacherListType[]>(); // 负责教师
const ParticipateTeacherList = ref<TeacherListType[]>(); // 参与教师
const filterateParticipateTeacherList = ref<TeacherListType[]>(); // 过滤参与教师
const ruleList = ref<RulePageVO[]>();
const route = useRoute();
const loadProgress = ref(0);
const progressFlag = ref(false);
const addTaskData = reactive<AddTaskDataRequest>({
  startTime: "",
});
interface classListType {
  id: number;
  name: string;
}
interface TeacherListType {
  userId: number;
  nickname: string;
  roleName: string;
}
// 提交表单规则
const rules = reactive({
  name: [{ required: true, message: "任务名称不能为空", trigger: "blur" }],
  classes: [{ required: true, message: "班级信息不能为空", trigger: "blur" }],
  ruleId: [{ required: true, message: "评阅规则不能为空", trigger: "blur" }],
  leader: [{ required: true, message: "负责教师不能为空", trigger: "blur" }],
  startTime: [
    { required: true, message: "启始时间信息不能为空", trigger: "blur" },
  ],
  endTime: [{ required: true, trigger: "blur", validator: endTimeValidator }],
});

// endTimeValidator(终止日期校验器)
function endTimeValidator(_rule: any, value: any, callback: any) {
  if (!value) {
    callback(new Error("终止日期信息不能为空"));
  } else if (value < addTaskData.startTime) {
    callback(new Error("终止日期应在启始日期之后"));
  } else {
    callback();
  }
}
// 过滤教师信息函数
function getteacherinfo() {
  GetTeacherInfo(courseId.value).then(({ data }) => {
    TeacherList.value = data;
    AdminTeacherList.value = TeacherList.value?.filter((item) => {
      return item.roleName === "协助者" || item.roleName === "创建者";
    });
    ParticipateTeacherList.value = TeacherList.value?.filter((item) => {
      return !(item.roleName === "创建者");
    });
    filterateParticipateTeacherList.value = ParticipateTeacherList.value;
  });
}
// 获取班级信息函数
function classlistinfo() {
  // 获取班级信息
  getclasslist(courseId.value).then(({ data }) => {
    classList.value = data;
  });
}
// 点击移出函数
function handleRemove(file: any, fileList: any) {
  ElMessageBox.confirm("确认删除此文件?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    // 过滤文件信息
    files.value = fileList.filter((item: any) => {
      return item.uid != file.uid;
    });
    // 过滤文件id信息
    filesId.value = filesId.value.filter((item: any) => {
      return item != file.raw.id;
    });
  });
}
// 改变行内信息函数（添加）
function changeleaderadd(e: any) {
  filterateParticipateTeacherList.value = ParticipateTeacherList.value!.filter(
    (item) => {
      return e != item.userId;
    }
  );
}
// 添加任务信息函数
function submit() {
  addTaskData.fileIds = filesId.value;
  AddTaskFrom.value.validate((valid: boolean) => {
    if (valid) {
      ElMessageBox.confirm("确认添加此任务?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(function () {
        addTaskData.assistants = ids.value;
        // 转换时间信息
        addTaskData.startTime = formatDate(
          new Date(addTaskData.startTime as string)
        );
        addTaskData.endTime = formatDate(
          new Date(addTaskData.endTime as string)
        );

        addExperimentTask(addTaskData, courseId.value)
          .then(() => {
            ElMessage.success("创建任务成功");
            router.push({ path: "/courseinfo/task" });
          })
          .catch((err) => {
            console.log(err);
          })
          .finally(() => {});
      });
    }
  });
}
// 取消添加任务函数
function cancellation() {
  router.push({
    path: "/courseinfo/task",
    query: {
      courseId: route.query.courseId,
    },
  });
}
// 行checkbox
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.userId);
}
// 上传成功函数
function handleSuccess3(res: any, file: any, fileList: any) {
  if (res.error === "") {
    console.log("成功");
  } else {
  }
}
// 文件信息改变时触发的函数
function handleChange(file: any, fileList: any) {
  // 文件上传前的操作
  if (!verifyFile(file, fileList)) return;
  file.status = "uploading";
  setTimeout(() => {
    loadProgress.value = 5;
  }, 100); // 一秒后关闭进度条
  setTimeout(() => {
    loadProgress.value = 10;
  }, 200); // 一秒后关闭进度条
  setTimeout(() => {
    loadProgress.value = 30;
  }, 300); // 一秒后关闭进度条
  setTimeout(() => {
    loadProgress.value = 50;
  }, 400); // 一秒后关闭进度条
  setTimeout(() => {
    loadProgress.value = 70;
  }, 500); // 一秒后关闭进度条
  setTimeout(() => {
    loadProgress.value = 80;
  }, 600); // 一秒后关闭进度条
  const reader = new FileReader();
  const spark = new SparkMD5.ArrayBuffer();
  reader.readAsArrayBuffer(file.raw);
  reader.onload = (e) => {
    spark.append(reader.result as ArrayBuffer);
    const md5 = spark.end();
    progressFlag.value = true;
    uploadExpAnnex(file.raw, md5, courseId.value)
      .then((res) => {
        loadProgress.value = 100;

        file.raw.id = res.data.id;
        file.path = res.data.path;
        file.url = res.data.url;
        files.value.push(file.raw as never);
        filesId.value.push(res.data.id as never);

        setTimeout(() => {
          progressFlag.value = false;
          loadProgress.value = 0;
          file.status = "success";
          ElMessage.success("文件上传成功");
        }, 1000); // 一秒后关闭进度条
      })
      .catch(() => {
        const index = fileList.indexOf(file);
        fileList.splice(index, 1);
        ElMessage.error("文件上传失败");
      });
  };
}

// 判断处理状态标签颜色函数
function status(label: string) {
  if (label === "协助者") {
    return "";
  } else {
    return "success";
  }
}
// 查询
function handleQuery() {
  // 获取班级信息
  getRuleByCourseId(courseId.value).then(({ data }) => {
    ruleList.value = data;
  });
}
// 进来就搜
onMounted(() => {
  courseId.value = courseStore.courseId;
  getteacherinfo();
  classlistinfo();
  handleQuery();
  // 隐藏展板
  appStore.sidebar.opened = false;
});
</script>

<style scoped lang="scss">
.PageHeader {
  border-bottom: 1px solid var(--el-bg-color);
  border-left: 1px solid var(--el-bg-color);
}

.btnlink {
  margin: 0 auto;
  text-align: center;
}
</style>
